﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ResearchRepository
{
	public partial class RRLogin : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			Title = GLOBALS.masterTitlePrefix + " - Login";
			// if already logged in, then redirect to account page
			if (Session[GLOBALS.userObjSessionVar] != null)
			{
				Response.Redirect("Account.aspx");
			}
		}
		protected void OnLoggingIn(object sender, LoginCancelEventArgs e)
		{
			//TODO: sanitize inputs
			Session[GLOBALS.userLoginSessionVar] = loginBox.UserName;
			Session[GLOBALS.passLoginSessionVar] = loginBox.Password;
		}
		protected void OnAuthenticate(object sender, AuthenticateEventArgs e)
		{
			try
			{
				Session[GLOBALS.userObjSessionVar] = RRDatabaseManager.getUser((string) Session[GLOBALS.userLoginSessionVar], (string) Session[GLOBALS.passLoginSessionVar]);
				e.Authenticated = Session[GLOBALS.userObjSessionVar] != null;
				loginBox.FailureText = "Invalid Username and/or Password";
			}
			catch (Exception x)
			{
				e.Authenticated = false;
				loginBox.FailureText = "Server Error";
				//TODO: report server error
			}
			finally
			{
				// always clear password after each sign-in attempt
				Session[GLOBALS.passLoginSessionVar] = null;
			}
		}
		protected void OnLoggedIn(object sender, EventArgs e)
		{
			//Session[GLOBALS.authorizedSessionVar] = true;
			Session[GLOBALS.rootFileSessionVar] = null;		// force browser file tree to refresh to show previously-hidden sub-dirs in dirs that have already been loaded
			Response.Redirect("Browse.aspx");
			//TODO: log user logins??
		}
		protected void OnLoginError(object sender, EventArgs e)
		{
		}
	}
}